package org.jbp.timelapse;

import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import android.hardware.Camera;
import android.os.AsyncTask;
import android.widget.ProgressBar;

public class TakePictureTask extends AsyncTask<Integer, TimeLapseProgressData, Void>
{
	private Camera camera;
	
	private LogTextView logView;
	private boolean logging;
	
	private ProgressBar pbTotal;
	private boolean progressing;
	
	public TakePictureTask(LogTextView logView, ProgressBar progressBar)
	{
		this.logView = logView;
		if(logView != null)
			this.logging = true;
		
		this.pbTotal = progressBar;
		if(progressBar != null)
		{
			this.pbTotal.setMax(100);
			this.progressing = true;
		}
	}
	
	@Override
	protected Void doInBackground(Integer... params)
	{
		if(params != null && params.length > 1)
		{
			try
			{
				publishProgress(new TimeLapseProgressData[]{new TimeLapseProgressData("Initializing camera.", 0d)});
				ThreadPoolExecutor executor = new ThreadPoolExecutor(1, 1, TimeLapseConstants.DEFAULT_INITIAL_DELAY, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>());
				executor.execute(new Runnable()
				{
					@Override
					public void run()
					{
						initCamera();
					}
				});
				Thread.sleep(TimeLapseConstants.DEFAULT_INITIAL_DELAY);
			}
			catch (InterruptedException e)
			{
				logError(e);
			}
			
			int nPic = params[0].intValue();
			int delay = params[1].intValue();
			long startTimestamp = System.currentTimeMillis();
			if(PictureLogger.getInstance() != null)
				PictureLogger.getInstance().logStart(nPic, delay, TimeLapseConstants.DEFAULT_INITIAL_DELAY, startTimestamp);
			try
			{
				for(int i = 0; i < nPic; i++)
				{
					String progressMessage = "Taking photo #"+(i+1)+" ... ";
					getCamera().takePicture(null, null, new TimeLapsePictureCallback(startTimestamp+"/"+SavePictureTask.getPictureName(i+1)));
					progressMessage += "SUCCESS";
					publishProgress(new TimeLapseProgressData[]{new TimeLapseProgressData(progressMessage, 1.0*i/nPic)});
					//TODO ni natancno. Zamenjaj s ScheduledThreadPoolExecutor.scheduleAtFixedRate(...)
					Thread.sleep(delay);
				}
				
				publishProgress(new TimeLapseProgressData[]{new TimeLapseProgressData("Finished.", 1)});
			}
			catch(InterruptedException e)
			{
				logError(e);
			}
			finally
			{
				getCamera().release();
			}
		}
		return null;
	}
	
	@Override
	protected void onProgressUpdate(TimeLapseProgressData... values)
	{
		if(values != null && values.length > 0)
		{
			logProgress(values[0]);
		}
	}
	
	private Camera getCamera()
	{
		if(camera == null)
		{
			camera = Camera.open();
		}
		return camera;
	}
	
	private void initCamera()
	{
		getCamera().startPreview();
	}
	
	private void logProgress(TimeLapseProgressData progress)
	{
		if(logging)
			logView.info(progress.getMessage());
		if(progressing)
			pbTotal.setProgress((int)(progress.getTotalProgress()*100));
	}
	
	private void logError(Exception e)
	{
		if(logging)
			logView.error(e.getMessage());
	}
}